package com.platform.user.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.common.annotation.ApiResponseBody;
import com.platform.common.entity.PageResult;
import com.platform.common.result.ApiException;
import com.platform.common.result.ApiExceptionEnum;
import com.platform.user.dto.UserDTO;
import com.platform.user.model.UserDO;
import com.platform.user.service.UserService;
import com.platform.user.vo.UserVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author shuc
 */
@ApiResponseBody
@Controller
@RequestMapping("/manage/user")
public class ManageController {

    @Resource
    private UserService userService;

    @GetMapping("/page")
    public PageResult<UserVO> page(@RequestParam Integer page,
                                   @RequestParam Integer size) {
        Page<UserDO> userDOPage = userService.page(page, size);
        return PageResult.<UserVO>builder()
                .total(userDOPage.getTotal())
                .rows(UserDO.toUserVOList(userDOPage))
                .build();
    }

    @PostMapping("/resetPwd")
    public Boolean resetPassword(@RequestBody Map<String, String> requestMap) {
        String id = requestMap.get("id");
        Boolean result = userService.updateById(
                UserDO.from(UserDTO.builder()
                        .id(id)
                        .password("123456")
                        .build()));
        if (!result) {
            throw new ApiException(ApiExceptionEnum.DB_FAIL);
        }
        return true;
    }

    @PostMapping("/updateRole")
    public Boolean updateRole(@RequestBody Map<String, String> requestMap) {
        String id = requestMap.get("id");
        String role = requestMap.get("role");
        Boolean result = userService.updateById(
                UserDO.from(UserDTO.builder()
                        .id(id)
                        .role(role)
                        .build()));
        if (!result) {
            throw new ApiException(ApiExceptionEnum.DB_FAIL);
        }
        return true;
    }

    @DeleteMapping("/delete")
    public Boolean delete(@RequestParam String id) {
        Boolean result = userService.removeById(id);
        if (!result) {
            throw new ApiException(ApiExceptionEnum.DB_FAIL);
        }
        return true;
    }
}
